package com.tungse;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import org.junit.Test;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author : Tungse
 * @Date: 2025/8/27 10:12
 * @Description:
 */
public class ThreadLocalTest {
    public static ThreadLocal<Student> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        Student student = new Student("张三", 1, "man");
        WeakReference<Student> wr = new WeakReference<>(student);
        Map<Student, String> map = new HashMap<>();
        map.put(wr.get(), "张三");

        System.out.println("wr = " + wr.get());
        System.out.println("map.get(wr) = " + map.get(student));

        System.out.println("第一次GC");
        System.gc();
        System.out.println("wr = " + wr.get());
        System.out.println("map.get(wr) = " + map.get(student));

        map.remove(student);
        student=null;
        System.out.println("第二次GC");
        System.gc();
        System.out.println("wr = " + wr.get());
        System.out.println("map.get(wr) = " + map.get(student));

    }

    @Test
    public void test001( ) {
        Student student = new Student("张三", 1, "man");
        WeakReference<Student> wr = new WeakReference<>(student);
        Map<Student, String> map = new HashMap<>();
        map.put(wr.get(), "张三");


        System.out.println("wr = " + wr.get());
        map = null;
        student = null;
        System.gc();
        System.out.println("wr = " + wr.get());
    }


    @Data
    @AllArgsConstructor
    @ToString
    public static class Student {
        private String name;
        private int age;
        private String sex;
    }
}

